package com.chuanjiabao.wisdom.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;

import com.chuanjiabao.wisdom.MainActivity;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.Constants;
import com.chuanjiabao.wisdom.bean.FamilyDeatilCallbackBean;
import com.chuanjiabao.wisdom.bean.HomeListCallBackBean;
import com.chuanjiabao.wisdom.bean.InviteListBean;
import com.chuanjiabao.wisdom.bean.ReasionInfoCallbackBean;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.bean.UpdateStatus;
import com.chuanjiabao.wisdom.databinding.FragmentIndexBinding;
import com.chuanjiabao.wisdom.greendao.gen.UpdateStatusDao;
import com.chuanjiabao.wisdom.guide.ComponentUtil;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.OnDataDoneListener;
import com.chuanjiabao.wisdom.listener.OnDataInviteListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.ui.activity.FamilyResActivity;
import com.chuanjiabao.wisdom.ui.activity.LoginActivity;
import com.chuanjiabao.wisdom.ui.activity.ShootActivity;
import com.chuanjiabao.wisdom.ui.activity.UpdateActivity;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.CreateFamilyDialog;
import com.chuanjiabao.wisdom.util.dialog.HintDeleteDialog;
import com.chuanjiabao.wisdom.util.dialog.HomeListDialog;
import com.chuanjiabao.wisdom.util.dialog.PermissionDialog;
import com.chuanjiabao.wisdom.util.dialog.TakeInInviteDialog;
import com.chuanjiabao.wisdom.util.dialog.TakeInheritDialog;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;

public class IndexFragment extends BaseLazyFragment {

    public static String permissionsId, uploadStatus;

    private FragmentIndexBinding binding;
    private CreateFamilyDialog dialog;
    private TakeInInviteDialog mDialog;
    private HomeListDialog homeListDialog;
    private TakeInheritDialog inheritDialog;

    private List<HomeListCallBackBean.DataBean> mHomeList = new ArrayList<>();
    private UpdateStatusDao updateStatusDao = FApplication.getInstance().getDaoSession().getUpdateStatusDao();

    //视频/图片选择
    private ReasionInfoCallbackBean.DataBean bean;

    private String homeId;
    private boolean hasRequest = false, isDismiss = false, hasGuide = false;
    private String hasHome = "0";
    private Disposable disposable;

    @Override
    public int setLayoutId() {
        return R.layout.fragment_index;
    }

    @SuppressLint("CheckResult")
    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(
                LayoutInflater.from(getActivity()),
                R.layout.fragment_index,
                container,
                false
        );
        binding.setFragment(this);

        EventBus.getDefault().register(this);

        disposable = Flowable.interval(5, 5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    if (binding.llModuleHint.getVisibility() == View.VISIBLE) {
                        Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_anim_2);
                        binding.llModuleHint.startAnimation(anim);
                    }
                });

        return binding.getRoot();
    }

    @Override
    protected void onVisible() {
        if (dialog != null) {
            dialog.dismiss();
        }

        if (homeListDialog != null) {
            homeListDialog.dismiss();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        bean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
        hasHome = bean.getHas_home() + "";

        binding.webView.setBackgroundColor(0);
        getHomeList(() -> {
            hasRequest = true;

            if (mHomeList.isEmpty()) {
                GlideUtil.setCircleMethod(
                        getActivity(),
                        SpResourceUtil.getHead(),
                        binding.ivModuleHead
                );

                userInvite((hasInvite, homeId, ids, names) -> {
                    if (hasInvite) {
                        showInviteDialog(homeId, ids, names, null);
                    } else {
                        if ((dialog == null || !dialog.isShowing()) && hasVisible()) {
                            dialog = new CreateFamilyDialog(getActivity());
                            dialog.show();
                            dialog.setOnBHClickListener(new OnBHClickListener() {
                                @Override
                                public void onCloseClick() {
                                    getHomeCreate();
                                }
                            });
                        }
                    }
                });
            } else {
                if (TextUtils.isEmpty(homeId)) {
                    int mLast = 0;
                    for (HomeListCallBackBean.DataBean item : mHomeList) {
                        if (item.getLast_one() == 1) {
                            setWebUrl(item.getId() + "");
                            mLast = 1;
                            break;
                        }
                    }

                    if (mLast == 0) {
                        setWebUrl(mHomeList.get(0).getId() + "");
                    }
                }

                userInvite((hasInvite, homeId, ids, names) -> {
                    if (hasInvite) showInviteDialog(homeId, ids, names, this::showInheritDialog);
                    else showInheritDialog();
                });
            }

        });
    }

    @Override
    protected void lazyLoad() {
        binding.llModuleCemare.setOnClickListener(this);
        binding.tvModuleMyHome.setOnClickListener(this);
        binding.llModuleUpdate.setOnClickListener(this);
        binding.llModuleQuery.setOnClickListener(this);
        binding.ivModuleHead.setOnClickListener(this);
        binding.ivModuleHint.setOnClickListener(this);

        if (mHomeList.isEmpty() && hasRequest) {
            userInvite((hasInvite, homeId, ids, names) -> {
                if (hasInvite) {
                    showInviteDialog(homeId, ids, names, null);
                } else {
                    if ((dialog == null || !dialog.isShowing()) && hasVisible()) {
                        dialog = new CreateFamilyDialog(getActivity());
                        dialog.show();
                        dialog.setOnBHClickListener(new OnBHClickListener() {
                            @Override
                            public void onCloseClick() {
                                getHomeCreate();
                            }
                        });
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivModuleHead:
                // startActivity(new Intent(getActivity(), UserInfoActivity.class));
                // showGuide();
                break;
            case R.id.ivModuleHint:
                isDismiss = true;
                binding.llModuleHint.setVisibility(View.GONE);
                break;
            case R.id.llModuleQuery:
                if (TextUtils.isEmpty(homeId)) return;

                if (TextUtils.equals("3", permissionsId)
                        && TextUtils.equals("0", uploadStatus)) {
                    showPermissionDialog();
                    return;
                }

                MainActivity main = (MainActivity) getActivity();
                main.setInfo(homeId);
                RxPermissions permissions = new RxPermissions(getActivity());
                permissions.request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA
                ).subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            startActivityForResult(new Intent(getActivity(), ShootActivity.class), 100);
                        } else {
                            ToastUtil.showToast("请开启读取权限");
                        }
                    }
                });
                break;
            case R.id.llModuleUpdate:
                if (TextUtils.isEmpty(homeId)) return;

                if (TextUtils.equals("3", permissionsId)
                        && TextUtils.equals("0", uploadStatus)) {
                    showPermissionDialog();
                    return;
                }

                startActivity(new Intent(getActivity(), UpdateActivity.class));
                break;
            case R.id.tvModuleMyHome:
                if (TextUtils.isEmpty(homeId)) return;

                homeListDialog = new HomeListDialog(getActivity(), hasHome);
                homeListDialog.show();
                homeListDialog.setOnHomeListClickListener(
                        (type, home, userId) -> {
                            switch (type) {
                                case "create": //创建
                                    if (dialog == null) {
                                        dialog = new CreateFamilyDialog(getActivity());
                                        dialog.show();
                                        dialog.setOnBHClickListener(new OnBHClickListener() {
                                            @Override
                                            public void onCloseClick() {
                                                getHomeCreate();
                                            }
                                        });
                                    } else dialog.show();
                                    break;
                                case "relation": //传承
                                    for (HomeListCallBackBean.DataBean item : mHomeList) {
                                        if (TextUtils.equals(home, item.getId() + "")) {
                                            TakeInheritDialog dialog = new TakeInheritDialog(
                                                    getActivity(),
                                                    item.getTruename(),
                                                    item.getAvatar()
                                            );
                                            dialog.show();
                                            dialog.setOnBHClickListener(style -> acceptInherit(home, style));
                                            break;
                                        }
                                    }
                                    break;
                                case "delete": //退出
                                    if (TextUtils.equals("-1", home)) return;

                                    if (TextUtils.equals(userId, SpResourceUtil.getUserId())) {
                                        ToastUtil.showToast("您当前是家管理者，暂无法退出该家");
                                        return;
                                    }

                                    new HintDeleteDialog(getActivity())
                                            .setTitle("退出家")
                                            .setContent("是否要退出该家")
                                            .setYes("确认退出")
                                            .setOnBHClickListener(new OnBHClickListener() {
                                                @Override
                                                public void onConfirmClick() {
                                                    getHomeExit(home);
                                                }
                                            })
                                            .show();
                                    break;
                                default:
                                    setWebUrl(home);
                                    break;
                            }
                        }
                );
                break;
            case R.id.llModuleCemare:
                if (TextUtils.isEmpty(homeId)) return;

                Intent intentHome = new Intent(getActivity(), FamilyResActivity.class);
                intentHome.putExtra("module_homeId", homeId);
                startActivity(intentHome);
                break;
            default:
        }
    }

    private void showPermissionDialog() {
        new PermissionDialog(getActivity())
                .setHint("对不起，您在该家没有上传权限")
                .show();
    }

    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled", "AddJavascriptInterface"})
    public void setWebViewInfo(String home, String userId) {
        String appCachePath = FApplication.getInstance().getCacheDir().getAbsolutePath();

        binding.webView.getSettings().setDomStorageEnabled(true);
        binding.webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        binding.webView.getSettings().setAppCachePath(appCachePath);
        binding.webView.getSettings().setAllowFileAccess(true);
        binding.webView.getSettings().setAppCacheEnabled(true);
        binding.webView.getSettings().setJavaScriptEnabled(true);
        binding.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        binding.webView.getSettings().setSupportZoom(true);
        binding.webView.getSettings().setBuiltInZoomControls(true);
        binding.webView.getSettings().setDisplayZoomControls(false);

        binding.webView.addJavascriptInterface(getActivity(), "android");
        binding.webView.setBackgroundColor(0);
        binding.webView.loadUrl(Constants.URL_HTML_ABOUT_BIHU + "?token=" + SpResourceUtil.getToken() +
                "&userId=" + userId +
                "&homeId=" + home +
                "&text=" + System.currentTimeMillis() +
                "#ponit_view");

        if (hasGuide) showGuide();
    }

    private void setWebUrl(String home) {
        homeId = home;
        SpUtils.put("module_homeId", homeId);

        List<UpdateStatus> updateStatusesList = updateStatusDao.loadAll();
        if (!updateStatusesList.isEmpty()) {
            if ("1".equals(updateStatusesList.get(0).getStatus())) {
                updateStatusDao.deleteAll();
            }
        }

        if (!TextUtils.isEmpty(homeId)) {
            for (HomeListCallBackBean.DataBean item : mHomeList) {
                String innerId = item.getId() + "";
                if (TextUtils.equals(homeId, innerId)) {
                    if (TextUtils.isEmpty(item.getAvatar())) {
                        binding.ivModuleHead.setImageResource(R.mipmap.icon_default_user);
                    } else {
                        GlideUtil.setCircleMethod(getActivity(), item.getAvatar(), binding.ivModuleHead);
                    }

                    String createId = item.getCreate_id() + "";
                    String adminId = item.getAdmin_id() + "";
                    if (TextUtils.equals(createId, SpResourceUtil.getUserId())) {
                        if (TextUtils.equals(
                                adminId,
                                SpResourceUtil.getUserId()
                        )) permissionsId = "1";
                        else permissionsId = "2";
                    } else {
                        if (TextUtils.equals(
                                adminId,
                                SpResourceUtil.getUserId()
                        )) permissionsId = "4";
                        else permissionsId = "3";
                    }
                }
            }
        }

        if (!TextUtils.equals("1", hasHome)
                && !TextUtils.isEmpty(homeId)
                && !isDismiss
        ) {
            binding.llModuleHint.setVisibility(View.VISIBLE);
        } else {
            binding.llModuleHint.setVisibility(View.GONE);
        }

        setWebViewInfo(homeId, SpResourceUtil.getUserId());
        getFamilyDetail();
    }

    private void showInviteDialog(
            String homeId,
            String ids,
            String names,
            OnDataDoneListener listener) {
        if ((mDialog == null || !mDialog.isShowing()) && hasVisible()) {
            mDialog = new TakeInInviteDialog(getActivity(), names);
            mDialog.setOnBHClickListener(new OnBHClickListener() {
                @Override
                public void onConfirmClick() {
                    acceptInvite(homeId, ids);
                }
            });
            mDialog.setOnDismissListener(dialog -> {
                if (listener != null && !mHomeList.isEmpty()) showInheritDialog();
            });
            mDialog.show();
        }
    }

    private void showInheritDialog() {
        for (HomeListCallBackBean.DataBean item : mHomeList) {
            if (item.getStatus() == 1 && hasVisible()) {
                if (inheritDialog != null && inheritDialog.isShowing()) return;
                inheritDialog = new TakeInheritDialog(
                        getActivity(),
                        item.getTruename(),
                        item.getAvatar()
                );
                inheritDialog.setOnBHClickListener(style -> acceptInherit(item.getId() + "", style));
                inheritDialog.show();
                break;
            }
        }
    }

    private void showGuide() {
        hasGuide = false;
        ComponentUtil.showEndGuide(
                getActivity(),
                R.mipmap.icon_guide02,
                "上传 - 图片，视频，文本",
                "将它们上传到家庭相册",
                binding.ivModuleUpdate, () ->
                        ComponentUtil.showEndGuide(
                                getActivity(),
                                R.mipmap.icon_guide03,
                                "速拍 - 快速调用手机拍摄视频图片",
                                "记录家庭精彩瞬间，无需再次上传",
                                binding.ivModuleQuery,
                                () ->
                                        ComponentUtil.showEndGuide(
                                                getActivity(),
                                                R.mipmap.icon_guide04,
                                                "相册 - 浏览您的家族相册",
                                                "所有上传，全部保留，永远留存",
                                                binding.ivModuleCemare,
                                                () ->
                                                        ComponentUtil.showStartCircelGuide(
                                                                getActivity(),
                                                                R.mipmap.icon_guide05,
                                                                "添加家人 - 添加这一辈份的家人",
                                                                "根据辈份添加，子孙后代关系不忘",
                                                                0,
                                                                binding.vModuleLeft,
                                                                () ->
                                                                        ComponentUtil.showStartCircelGuide(
                                                                                getActivity(),
                                                                                R.mipmap.icon_guide06,
                                                                                "添加辈份 - 添加一个长辈或晚辈",
                                                                                "精细化的添加，完善您的家庭树",
                                                                                10,
                                                                                binding.vModuleTop,
                                                                                () ->
                                                                                        ComponentUtil.showStartGuide(
                                                                                                getActivity(),
                                                                                                R.mipmap.icon_guide07,
                                                                                                "切换家庭 - 多个家庭随意切换",
                                                                                                "家是最小国，国是千万家",
                                                                                                15,
                                                                                                binding.tvModuleMyHome,
                                                                                                () ->
                                                                                                        ComponentUtil.showCenterGuide(
                                                                                                                getActivity(),
                                                                                                                binding.vModuleCenter
                                                                                                        )
                                                                                        )
                                                                        )
                                                        )

                                        )
                        )
        );
    }

    // 家邀请
    public void userInvite(OnDataInviteListener listener) {
        HTTPAPI.getInstance().userInvite(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    try {
                        JSONObject json = new JSONObject(s);
                        int code = (int) json.get("code");
                        if (code == 1001) {
                            startActivity(new Intent(getActivity(), LoginActivity.class));
                        } else {
                            String msg = (String) json.get("msg");
                            ToastUtil.showToast(msg);
                            listener.onNext(false, null, null, null);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    InviteListBean callBackBean = GsonUtil.GsonToBean(s, InviteListBean.class);
                    if (callBackBean != null) {
                        List<InviteListBean.DataBean> items = callBackBean.getData();
                        if (items != null && !items.isEmpty()) {
                            StringBuilder names = new StringBuilder();
                            StringBuilder ids = new StringBuilder();
                            for (InviteListBean.DataBean item : items) {
                                names.append(item.getTruename()).append(",");
                                ids.append(item.getId()).append(",");
                            }

                            listener.onNext(
                                    true,
                                    items.get(0).getHome_id(),
                                    ids.substring(0, ids.length() - 1),
                                    names.substring(0, names.length() - 1)
                            );
                        } else {
                            listener.onNext(false, null, null, null);
                        }
                    } else {
                        listener.onNext(false, null, null, null);
                    }
                }
            }
        });
    }

    // 接受家邀请
    public void acceptInvite(String home, String ids) {
        HTTPAPI.getInstance().endInvite(ids, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    setWebUrl(home);
                }
            }
        });
    }

    // 接受传承邀请
    public void acceptInherit(String home, String secret) {
        HTTPAPI.getInstance().endInherit(secret, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    setWebUrl(home);
                    getHomeList(null);
                }
            }
        });
    }

    // 获取家列表
    public void getHomeList(OnDataDoneListener listener) {
        HTTPAPI.getInstance().getHomeList(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    HomeListCallBackBean callBackBean = GsonUtil.GsonToBean(s, HomeListCallBackBean.class);
                    if (callBackBean != null) {
                        List<HomeListCallBackBean.DataBean> data = callBackBean.getData();
                        if (data != null) {
                            mHomeList.clear();
                            mHomeList.addAll(data);
                            if (listener != null) listener.onNext();
                        }
                    }
                }
            }
        });
    }

    // 创建家
    public void getHomeCreate() {
        HTTPAPI.getInstance().getHomeCreate(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    hasHome = "1";
                    bean.setHas_home(1);
                    SpUtils.putBean("module_reasion", bean);
                    hasGuide = true;

                    getHomeList(() -> setWebUrl(homeId = mHomeList.get(0).getId() + ""));
                }
            }
        });
    }

    // 退出家
    public void getHomeExit(String id) {
        HTTPAPI.getInstance().getHomeExit(id, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    HomeListCallBackBean.DataBean data = null;
                    for (HomeListCallBackBean.DataBean item : mHomeList) {
                        if (TextUtils.equals(id, item.getId() + "")) {
                            data = item;
                            break;
                        }
                    }

                    if (data != null) {
                        mHomeList.remove(data);
                        if (TextUtils.equals(homeId, id)) {
                            if (!mHomeList.isEmpty()) setWebUrl(mHomeList.get(0).getId() + "");
                            else {
                                homeId = "";
                                binding.webView.loadUrl("");
                            }
                        } else {
                            if (mHomeList.isEmpty()) {
                                homeId = "";
                                binding.webView.loadUrl("");
                            }
                        }
                    }
                }
            }
        });
    }

    //个人信息
    private void getUserInfo() {
        HTTPAPI.getInstance().getUserInfo(SpResourceUtil.getToken(), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    ReasionInfoCallbackBean bean = GsonUtil.GsonToBean(s, ReasionInfoCallbackBean.class);
                    SpUtils.putBean("module_reasion", bean.getData());
                    SpUtils.put("module_userId", bean.getData().getId() + "");
                    SpUtils.put("module_truename", bean.getData().getTruename());
                    SpUtils.put("module_userinfo_head", bean.getData().getAvatar());
                }
            }
        });
    }

    //家里给人详情
    private void getFamilyDetail() {
        HTTPAPI.getInstance().getFamilyDetail(homeId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    try {
                        FamilyDeatilCallbackBean callbackBean = GsonUtil.GsonToBean(s, FamilyDeatilCallbackBean.class);
                        for (FamilyDeatilCallbackBean.DataBean dataBean : callbackBean.getData()) {
                            for (FamilyDeatilCallbackBean.DataBean.MembersBean membersBean : dataBean.getMembers()) {
                                if (SpResourceUtil.getUserId().equals(membersBean.getD_user_id() + "")) {
                                    uploadStatus = membersBean.getD_pic_upload() + "";
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Subscribe
    public void onMessageEvent(RefreshMessageEvent event) {
        if (!TextUtils.isEmpty(homeId)
                && TextUtils.equals("refresh", event.getType())) {
            setWebUrl(homeId);
        }
    }

    private Boolean hasVisible() {
        return getUserVisibleHint() && isResumed();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (disposable != null) disposable.dispose();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.webView.clearHistory();
        binding.webView.clearCache(true);
        binding.webView.freeMemory();
        binding.webView.destroy();
        EventBus.getDefault().unregister(this);
    }

}
